package com.jww.cloud.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.jww.base.am.model.dos.SysRoleDO;
import com.jww.base.am.model.dos.SysUserDO;
import com.jww.common.core.constant.enums.EnabledStatusEnum;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;

/**
 * 用户详情实现类
 *
 * @author wanyong
 * @date 2018/9/24 15:09
 */
public class UserDetailsImpl implements UserDetails {

    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private Long userId;

    @Getter
    @Setter
    private String username;

    @Getter
    @Setter
    private String password;

    @Getter
    @Setter
    private Integer status;

    @Getter
    @Setter
    private List<SysRoleDO> roleList;

    public UserDetailsImpl(SysUserDO sysUserDO) {
        this.userId = sysUserDO.getId();
        this.username = sysUserDO.getUsername();
        this.password = sysUserDO.getPassword();
        this.status = sysUserDO.getIsEnable();
        this.roleList = sysUserDO.getRoleList();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorityList = CollUtil.newArrayList();
        if (!CollectionUtils.isEmpty(this.roleList)) {
            for (SysRoleDO sysRoleDO : this.roleList) {
                authorityList.add(new SimpleGrantedAuthority(sysRoleDO.getRoleCode()));
            }
        }
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return status.equals(EnabledStatusEnum.ENABLE.value());
    }
}
